package com.six.backend.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


import com.six.backend.pojo.Role;
import com.six.backend.service.RoleService;
import com.six.backend.shiro.Utils.Result;
import com.six.backend.utils.RedisUtil;
import com.six.backend.utils.TimeUtil;
import com.six.backend.utils.TokenUtil;
import com.six.backend.annotation.OperLog;
import com.six.backend.pojo.Authority;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 张重阳
 * @Date 2021-11-13 0:03
 * @Version 1.0
 */

@Slf4j
@RestController
@Transactional(rollbackFor=Exception.class)
@RequestMapping(produces = "application/json;charset = utf-8")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisUtil redisUtil;


    @GetMapping("/getRoles")
    @ApiOperation("获取角色")
    @OperLog(operModule = "系统管理模块",operType = "get",operDesc = "获取角色信息操作")
    public Result getRoles(@RequestParam(value = "account", required = false) String account,
                           @RequestParam(value = "name", required = false) String name,
                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", required = false) Integer pageSize,
                           HttpServletRequest request) {
        String account1 = TokenUtil.getTokenName(request);
        Map map = new HashMap<>();
        if (account != "") {
            map.put("account",account);
        }
        if (name != "") {
            map.put("name",name);
        }
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum,pageSize);
            List<Role> list = roleService.selectRoles(map);
            return new Result<>().setCode(200).setData(new PageInfo<>(list)).setMessage("查询角色成功");
        }else {
            List<Role> list = roleService.selectRoles(map);
            return new Result<>().setCode(200).setData(new PageInfo<>(list)).setMessage("查询角色成功");
        }
//        List<Role> roles = roleService.selectRoles(map);
//        ArrayList<Map> list = new ArrayList<>();
//        for (Role role : roles) {
//            Map map1 = new HashMap<>(2);
//            map1.put("value",role.getName());
//            map1.put("label",role.getName());
//            list.add(map1);
//        }
//        return new Result().setCode(200).setMessage("查询角色成功").setData(list);
    }

    @PostMapping("/addRole")
    @ApiOperation("创建角色")
    @OperLog(operModule = "系统管理模块",operType = "post",operDesc = "创建角色模块")
    public Result addRole(@RequestBody Map map, HttpServletRequest servletRequest){
        String name = map.get("name").toString();
        if (roleService.isExist(name)) {
            return new Result<>().setCode(202).setMessage("角色已存在");
        }else {
            // 获取创建人
            String account = TokenUtil.getTokenName(servletRequest);
            map.put("creator", account);
            // 设置创建时间
            map.put("createTime", new TimeUtil().getTime());
            if (roleService.insertRole(map)) {
                return new Result<>().setCode(201).setMessage("创建角色成功");
            }else {
                return new Result<>().setCode(403).setMessage("创建失败");
            }
        }
    }

    @PostMapping("/editRole")
    @ApiOperation("编辑角色")
    @OperLog(operModule = "系统管理模块",operType = "post",operDesc = "编辑角色操作")
    public Result editRole(@RequestBody Role role) {
        if (roleService.updateRole(role)) {
            return new Result<>().setCode(200).setMessage("角色修改成功");
        }
        return new Result<>().setCode(202).setMessage("角色修改失败");
    }


    @GetMapping("/getRoleAuthority")
    @ApiOperation("获取角色已有权限")
    @OperLog(operModule = "系统管理模块",operType = "get",operDesc = "获取角色已有权限操作")
    public Result getRoleAuthority(@RequestParam("name") String roleName){
        Result result = new Result<>();
        if (roleName == "") {
            return result.setCode(403).setMessage("角色名为空");
        }
        List<Authority> authorityList = roleService.selectPermissionByRoleName(roleName);
        return result.setCode(200).setMessage("角色权限获取成功").setData(authorityList);
    }

    @GetMapping("/getOtherRoleAuthority")
    @ApiOperation("获取角色未有权限")
    @OperLog(operModule = "系统管理模块",operType = "get",operDesc = "获取角色未有权限操作")
    public Result getOtherRoleAuthority(@RequestParam("name") String roleName){
        Result result = new Result<>();
        if (roleName == "") {
            return result.setCode(403).setMessage("角色名为空");
        }
        List<Authority> authorityList = roleService.selectOtherPermissionByRoleName(roleName);
        return result.setCode(200).setMessage("角色未有权限获取成功").setData(authorityList);
    }

    @PostMapping("/editRoleAuthority")
    @ApiOperation("修改角色权限")
    @OperLog(operModule = "系统管理模块",operType = "get",operDesc = "修改角色权限操作")
    public Result editRoleAuthority(@RequestBody Map map) {
        String roleName = (String)map.get("name");
        // 将指定json格式的权限列表转化为string类型
        String s = JSON.toJSONString(map.get("toData"));
        System.out.println(s);
        // 将string类型转化为Authority的list
        List<Authority> authorityList = JSONObject.parseArray(s, Authority.class);
        if (authorityList != null) {
            if (roleService.editPermissionOfRoleName(roleName,authorityList)) {
                // 清除该角色在redis中的缓存
                try {
                    redisUtil.del(roleName);
                } catch (Exception e) {
                    System.out.println("未连接到Redis");
                }
                return new Result().setCode(200).setMessage("权限修改成功");
            }
            return new Result().setCode(202).setMessage("权限修改失败");
        }
        return new Result().setCode(406).setMessage("未获取到修改的权限信息");
    }


    @DeleteMapping("/deleteRole")
    @ApiOperation("删除角色")
    public Result deleteRole(@RequestParam("name") String roleName) {
        if (!roleService.isRoleUsed(roleName)) {
            if (roleService.deleteRole(roleName)) {
                return new Result<>().setCode(200).setMessage("角色删除成功");
            }
            return new Result<>().setCode(202).setMessage("角色删除失败");
        }
        return new Result<>().setCode(202).setMessage("该角色已被使用，无法删除");
    }




}
